#!/usr/bin/env python3
"""
多错误类型测试脚本
"""

import requests
import json
import sys
import os
import random
import time
from pathlib import Path

def upload_sample_logs():
    """上传示例日志文件"""
    print("📤 上传示例日志文件...")
    
    sample_file = "sample_logs.tar.gz"
    if not os.path.exists(sample_file):
        print(f"[FAIL] 示例文件 {sample_file} 不存在")
        return False
    
    try:
        with open(sample_file, 'rb') as f:
            files = {'file': (sample_file, f, 'application/gzip')}
            response = requests.post("http://localhost:8080/upload", files=files, timeout=30)
        
        if response.status_code == 200:
            result = response.json()
            print(f"[PASS] 示例日志上传成功")
            print(f"   总日志数: {result.get('total_logs', 0)}")
            return True
        else:
            print(f"[FAIL] 示例日志上传失败: {response.status_code}")
            print(f"   错误信息: {response.text}")
            return False
    except Exception as e:
        print(f"[FAIL] 示例日志上传失败: {e}")
        return False

def get_error_categories():
    """获取错误分类列表"""
    print("[SEARCH] 获取错误分类...")
    
    try:
        response = requests.get("http://localhost:8080/ai/error-categories", timeout=10)
        if response.status_code == 200:
            categories = response.json()
            print(f"[PASS] 获取错误分类成功")
            print(f"   找到 {len(categories)} 个错误分类:")
            for category in categories:
                print(f"   - {category['name']}: {category['count']} 条日志")
            return categories
        else:
            print(f"[FAIL] 获取错误分类失败: {response.status_code}")
            return []
    except Exception as e:
        print(f"[FAIL] 获取错误分类失败: {e}")
        return []

def test_error_analysis(category_name):
    """测试特定错误类型分析"""
    print(f"[SEARCH] 测试 {category_name} 错误分析...")
    
    try:
        data = {"error_category": category_name}
        response = requests.post("http://localhost:8080/ai/analyze", json=data, timeout=60)
        
        if response.status_code == 200:
            result = response.json()
            if 'initial_analysis' in result:
                print("[PASS] 错误类型分析成功")
                print(f"   错误类型: {result.get('error_category', category_name)}")
                print(f"   错误数量: {result.get('error_count', 0)}")
                print(f"   分析结果长度: {len(result['initial_analysis'])} 字符")
                return True
            else:
                print("[FAIL] 分析结果异常")
                return False
        else:
            print(f"[FAIL] 错误类型分析失败: {response.status_code}")
            print(f"   错误信息: {response.text}")
            return False
    except Exception as e:
        print(f"[FAIL] 错误类型分析失败: {e}")
        return False

def test_random_errors(categories, count=3):
    """随机测试多个错误类型"""
    print(f"🎲 随机测试 {count} 个错误类型...")
    
    if len(categories) < count:
        count = len(categories)
        print(f"[WARN]  只有 {count} 个错误类型可用")
    
    # 随机选择错误类型
    selected_categories = random.sample(categories, count)
    
    success_count = 0
    for i, category in enumerate(selected_categories, 1):
        print(f"\n📋 测试 {i}/{count}: {category['name']}")
        if test_error_analysis(category['name']):
            success_count += 1
        else:
            print(f"[FAIL] {category['name']} 测试失败")
        
        # 添加延迟，避免API调用过于频繁
        if i < count:
            time.sleep(2)
    
    return success_count, count

def test_all_errors(categories):
    """测试所有错误类型"""
    print(f"[SEARCH] 测试所有 {len(categories)} 个错误类型...")
    
    success_count = 0
    for i, category in enumerate(categories, 1):
        print(f"\n📋 测试 {i}/{len(categories)}: {category['name']}")
        if test_error_analysis(category['name']):
            success_count += 1
        else:
            print(f"[FAIL] {category['name']} 测试失败")
        
        # 添加延迟，避免API调用过于频繁
        if i < len(categories):
            time.sleep(2)
    
    return success_count, len(categories)

def main():
    """主测试函数"""
    print("[TEST] 多错误类型分析测试")
    print("=" * 50)
    
    # 检查后端服务
    try:
        response = requests.get("http://localhost:8080/", timeout=5)
        if response.status_code != 200:
            print("[FAIL] 后端服务未正常运行")
            sys.exit(1)
    except:
        print("[FAIL] 后端服务未启动，请先启动后端服务")
        print("   运行: python app.py")
        sys.exit(1)
    
    # 上传示例日志文件
    if not upload_sample_logs():
        print("\n[FAIL] 示例日志上传失败，无法继续测试")
        print("   请确保 sample_logs.tar.gz 文件存在")
        sys.exit(1)
    
    # 等待系统处理日志
    print("[WAIT] 等待系统处理日志...")
    time.sleep(2)
    
    # 获取错误分类
    categories = get_error_categories()
    
    if not categories:
        print("\n[FAIL] 没有找到错误分类，请检查日志文件格式")
        print("   请确保日志文件包含错误信息")
        sys.exit(1)
    
    # 询问用户选择测试模式
    print(f"\n[STATS] 找到 {len(categories)} 个错误类型:")
    for i, category in enumerate(categories, 1):
        print(f"   {i}. {category['name']} ({category['count']} 条日志)")
    
    print("\n选择测试模式:")
    print("1. 随机测试 3 个错误类型")
    print("2. 测试所有错误类型")
    print("3. 手动选择错误类型")
    
    try:
        choice = input("\n请输入选择 (1/2/3): ").strip()
        
        if choice == "1":
            success_count, total_count = test_random_errors(categories, 3)
        elif choice == "2":
            success_count, total_count = test_all_errors(categories)
        elif choice == "3":
            print("\n可选的错误类型:")
            for i, category in enumerate(categories, 1):
                print(f"   {i}. {category['name']}")
            
            try:
                choice_num = int(input("请输入错误类型编号: ")) - 1
                if 0 <= choice_num < len(categories):
                    selected_category = categories[choice_num]['name']
                    print(f"🎯 选择测试: {selected_category}")
                    test_error_analysis(selected_category)
                    success_count, total_count = 1, 1
                else:
                    print("[FAIL] 无效的选择")
                    sys.exit(1)
            except ValueError:
                print("[FAIL] 请输入有效的数字")
                sys.exit(1)
        else:
            print("[FAIL] 无效的选择")
            sys.exit(1)
        
        print(f"\n" + "=" * 50)
        print("[SUCCESS] 多错误类型分析测试完成!")
        print(f"\n[STATS] 测试结果:")
        print(f"   成功: {success_count}/{total_count}")
        print(f"   成功率: {(success_count/total_count)*100:.1f}%")
        
        if success_count == total_count:
            print("   [SUCCESS] 所有测试通过!")
        elif success_count > 0:
            print("   [WARN]  部分测试通过")
        else:
            print("   [FAIL] 所有测试失败")
        
    except KeyboardInterrupt:
        print("\n\n⏹️  测试被用户中断")
        sys.exit(0)

if __name__ == "__main__":
    main() 